<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入活动标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动分类" prop="categoryId">
        <category-select
          v-model="queryParams.categoryId"
          placeholder="请选择活动分类"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="活动状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['secondclass:activity:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['secondclass:activity:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['secondclass:activity:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['secondclass:activity:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动ID" align="center" prop="activityId" width="80" />
      <el-table-column label="活动标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="活动分类" align="center" prop="categoryName" width="120" />
      <el-table-column label="活动地点" align="center" prop="location" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名人数上限" align="center" prop="maxParticipants" width="100" />
      <el-table-column label="活动学分" align="center" prop="creditValue" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">{{ scope.row.statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['secondclass:activity:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['secondclass:activity:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="handleCommand" trigger="click">
            <span class="el-dropdown-link">
              <i class="el-icon-arrow-down el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                :command="{ type: 'approve', row: scope.row }" 
                v-if="scope.row.status === '0'"
                v-hasPermi="['secondclass:activity:edit']"
              >审核通过</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'reject', row: scope.row }" 
                v-if="scope.row.status === '0'"
                v-hasPermi="['secondclass:activity:edit']"
              >审核拒绝</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'cancel', row: scope.row }" 
                v-if="scope.row.status === '1'"
                v-hasPermi="['secondclass:activity:edit']"
              >取消活动</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'end', row: scope.row }" 
                v-if="scope.row.status === '1'"
                v-hasPermi="['secondclass:activity:edit']"
              >结束活动</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'addEnrollment', row: scope.row }" 
                v-hasPermi="['secondclass:enrollment:add']"
              >添加报名</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'viewEnrollments', row: scope.row }" 
                v-hasPermi="['secondclass:enrollment:list']"
              >查看报名列表</el-dropdown-item>
              <el-dropdown-item 
                :command="{ type: 'addCredit', row: scope.row }" 
                v-hasPermi="['secondclass:credit:add']"
              >添加学分记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动分类" prop="categoryId">
          <category-select v-model="form.categoryId" placeholder="请选择活动分类" />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报名开始时间" prop="signupStartTime">
              <el-date-picker
                v-model="form.signupStartTime"
                type="datetime"
                placeholder="选择报名开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名结束时间" prop="signupEndTime">
              <el-date-picker
                v-model="form.signupEndTime"
                type="datetime"
                placeholder="选择报名结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大参与人数" prop="maxParticipants">
              <el-input-number v-model="form.maxParticipants" :min="1" :max="10000" controls-position="right" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动学分" prop="creditValue">
              <el-input-number v-model="form.creditValue" :min="0.01" :max="10" :precision="2" :step="0.1" controls-position="right" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入活动描述" :rows="5" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listActivity, getActivity, addActivity, updateActivity, updateActivityStatus, delActivity } from "@/api/secondclass/activity";
import CategorySelect from "@/components/CategorySelect";

export default {
  name: "Activity",
  components: { CategorySelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 活动信息表格数据
      activityList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态类型映射
      statusTypeMap: {
        "0": "info",
        "1": "success",
        "2": "danger",
        "3": "warning",
        "4": "info"
      },
      // 状态数据字典
      statusOptions: [
        {
          dictLabel: "待审核",
          dictValue: "0"
        },
        {
          dictLabel: "已通过",
          dictValue: "1"
        },
        {
          dictLabel: "已拒绝",
          dictValue: "2"
        },
        {
          dictLabel: "已取消",
          dictValue: "3"
        },
        {
          dictLabel: "已结束",
          dictValue: "4"
        }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        categoryId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "活动标题不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "活动分类不能为空", trigger: "change" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        signupStartTime: [
          { required: true, message: "报名开始时间不能为空", trigger: "blur" }
        ],
        signupEndTime: [
          { required: true, message: "报名结束时间不能为空", trigger: "blur" }
        ],
        creditValue: [
          { required: true, message: "活动学分不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询活动信息列表 */
    getList() {
      this.loading = true;
      listActivity(this.queryParams).then(response => {
        this.activityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        title: null,
        categoryId: null,
        description: null,
        location: null,
        startTime: null,
        endTime: null,
        signupStartTime: null,
        signupEndTime: null,
        maxParticipants: 100,
        creditValue: 1.00,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.activityId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const activityId = row.activityId || this.ids[0];
      getActivity(activityId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改活动信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.activityId != null) {
            updateActivity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const activityIds = row.activityId || this.ids;
      this.$modal.confirm('是否确认删除活动信息编号为"' + activityIds + '"的数据项?').then(function() {
        return delActivity(activityIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('secondclass/activity/export', {
        ...this.queryParams
      }, `activity_${new Date().getTime()}.xlsx`);
    },
    /** 处理下拉菜单命令 */
    handleCommand(command) {
      const { type, row } = command;
      switch (type) {
        case 'approve':
          this.handleUpdateStatus(row, '1');
          break;
        case 'reject':
          this.handleUpdateStatus(row, '2');
          break;
        case 'cancel':
          this.handleUpdateStatus(row, '3');
          break;
        case 'end':
          this.handleUpdateStatus(row, '4');
          break;
        case 'addEnrollment':
          this.handleAddEnrollment(row);
          break;
        case 'viewEnrollments':
          this.handleViewEnrollments(row);
          break;
        case 'addCredit':
          this.handleAddCredit(row);
          break;
        default:
          break;
      }
    },
    /** 更新活动状态 */
    handleUpdateStatus(row, status) {
      const statusMap = {
        '1': '审核通过',
        '2': '审核拒绝',
        '3': '取消',
        '4': '结束'
      };
      this.$modal.confirm('确认要' + statusMap[status] + '该活动吗?').then(() => {
        return updateActivityStatus(row.activityId, status);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(statusMap[status] + "成功");
      }).catch(() => {});
    },
    /** 添加报名 */
    handleAddEnrollment(row) {
      this.$router.push({ 
        path: '/secondclass/enrollment/add', 
        query: { activityId: row.activityId } 
      });
    },
    /** 查看报名列表 */
    handleViewEnrollments(row) {
      this.$router.push({ 
        path: '/secondclass/enrollment', 
        query: { activityId: row.activityId } 
      });
    },
    /** 添加学分记录 */
    handleAddCredit(row) {
      this.$router.push({ 
        path: '/secondclass/credit/add', 
        query: { activityId: row.activityId } 
      });
    }
  }
};
</script>
